<?php

namespace App\Services;

use App\Http\Resources\Admin\AdminResource\Admin as AdminResource;
use App\Http\Resources\Estate\AdminEstateResource\Admin as AdminEstateResource;
use App\Http\Resources\Home\UserResource\UserCheckLogin;
use App\Models\Admin;
use App\Models\AdminEstate;
use App\Models\Community;
use App\Models\SmsLog;
use App\Models\Store;
use App\Models\User;
use App\Models\UserWechat;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserService extends BaseService
{

    public $model;

    public function __destruct()
    {
        $this->model = new User();
    }


    // login
    public function login($username = 'username', $auth = 'user')
    {
        $credentials = request([$username, 'password']);
        if (!$token = auth($auth)->attempt($credentials)) {
            return $this->format_error(__('auth.error'));
        }
        if (!$userInfo = $this->getUserInfo($auth)) {
            return $this->format_error(__('auth.user_error'));
        }
        // 登陆成功修改时间和ip
        if ($auth == 'admin') {
            $admin_model = Admin::find($userInfo['id']);
            $admin_model->login_time = now();
            $admin_model->last_login_time = $userInfo['login_time'];
            $admin_model->ip = request()->getClientIp();
            $admin_model->save();
        }
        if ($auth == 'user') {
            $user_model = User::find($userInfo['id']);
            if ($user_model['status'] == 0) {
                return $this->format_error(__('auth.no_examine'));
            }
            $user_model->login_time = now();
            $user_model->last_login_time = $userInfo['login_time'];
            $user_model->ip = request()->getClientIp();
            $user_model->save();

            // 登录送积分
            $config_service = new ConfigService();
            $config_service->giveIntegral('login');
        }

        if ($auth == 'estate') {
            $user_model = AdminEstate::find($userInfo['id']);
            $user_model->login_time = now();
            $user_model->last_login_time = $userInfo['login_time'];
            $user_model->ip = request()->getClientIp();
            $user_model->save();

        }

        $data = [
            'token' => $token,
            'user_info' => $userInfo,
        ];
        return $this->format($data);
    }

    // 第三方登录
    public function getUserInfo($auth = 'user')
    {
        try {
            $info = auth($auth)->user();
            if ($auth == 'admin') {
                return new AdminResource($info);
            }

            if ($auth == 'estate') {
                return new AdminEstateResource($info);
            }
            return $info;
        } catch (\Exception $e) {
            return false;
        }
    }

    // 注册

    public function oauthLogin($oauth, $oauth_name = "weixinweb")
    {
        $user_model = new User();
        $auth = 'user';

        try {
            DB::beginTransaction();
            // 判断是否存在该ID
            if ($oauth_name == 'weixinweb') {
                $isLogin = false; // 登录还是注册
                $uw_model = new UserWechat();
                $uwInfo = $uw_model->where('unionid', $oauth['unionid'])->fisrt();

                // 不存在则开始创建
                if (!$uwInfo) {
                    $user_model->username = 'wx' . date('Ymd') . mt_rand(100, 999);
                    $user_model->nickname = $oauth['nickname'];
                    $user_model->ip = request()->getClientIp();
                    $user_model->inviter_id = request()->inviter_id ?? 0;
                    $user_model->password = Hash::make('123456');
                    $user_model->pay_password = Hash::make('123456');
                    $user_model->save();
                    $user_id = $user_model->id;

                    // 插入第三方表
                    $uw_model->create([
                        'openid' => $oauth['id'],
                        'nickname' => $oauth['nickname'],
                        'user_id' => $user_id,
                        'unionid' => $oauth['unionid'],
                        'headimgurl' => $oauth['avatar'],
                    ]);
                } else {
                    $isLogin = true;
                    $user_id = $uw_model['user_id'];
                }

            }

            $user_info = User::select('username', 'password')->where('id', $user_id)->first();

            $user_model->login_time = now();
            $user_model->last_login_time = $user_info['login_time'];
            $user_model->ip = request()->getClientIp();
            $user_model->save();

            if (!$token = auth($auth)->login($user_info)) {
                return $this->format_error(__('auth.error'));
            }

            if (!$userInfo = $this->getUserInfo($auth)) {
                return $this->format_error(__('auth.user_error'));
            }

            // 登录送积分
            $config_service = new ConfigService();
            $config_service->giveIntegral('login');

            $data = [
                'token' => $token,
                'user_info' => $userInfo,
            ];

            // 提交事务
            DB::commit();
            return $this->format($data);
        } catch (\Exception $e) {
            return $this->format_error($e->getMessage());
        }


    }

    /**
     * 注册
     * @param string $username
     * @param string $auth
     * @return array
     */
    public function register($username = 'username', $auth = 'user')
    {

        //企业名称 store_name
        //法人代表 legal_person
        //企业详细地址 store_address
        //注册资本 registered_capital
        //成立日期 date_of_establishment
        //联系人 emergency_contact
        //联系电话 emergency_contact_phone
        // //统一信用代码 business_license_no
        //营业执照 business_license
        //有效期 valid_period
        //一般纳税人证明 general_taxpayer_certificate
        $arr = [
            'username' => request()->username,
            'password' => request()->password,
            're_password' => request()->re_password,
            'code' => request()->code
        ];
        $arr1 = [];
        switch ($auth) {
            case "user":
                $arr1 = [
                    'store_name' => request()->store_name,//商家名称
                    'legal_person' => request()->legal_person,//法人代表
                    'store_address' => request()->store_address,//详细地址
                    'registered_capital' => request()->registered_capital,//注册资本
                    'date_of_establishment' => request()->date_of_establishment,//成立时间
                    'emergency_contact' => request()->emergency_contact,//联系人
                    'emergency_contact_phone' => request()->emergency_contact_phone,//联系人电话
                    'business_license_no' => request()->business_license_no,//营业执照号(统一信用代码)
                    'business_license' => request()->business_license,//营业执照图片
                    'valid_period' => request()->valid_period,//营业执照有效期
                    'general_taxpayer_certificate' => request()->general_taxpayer_certificate,//一般纳税人证明，
                    'class_id' => request()->class_id,
                    'community_id' => request()->community_id,
                    'email' => request()->email,
                    'store_verify' => 2,
                    'customer_server_phone' => request()->customer_server_phone
                ];
                break;
            case "applets":
                $arr1 = [];
                break;
            default:
                break;
        }
        //企业名称 store_name
        //法人代表 legal_person
        //企业详细地址 store_address
        //注册资本 registered_capital
        //成立日期 date_of_establishment
        //联系人 emergency_contact
        //联系电话 emergency_contact_phone
        // //统一信用代码 business_license_no
        //营业执照 business_license
        //有效期 valid_period
        //一般纳税人证明 general_taxpayer_certificate

        $validator = Validator::make($arr1, [
            'store_name' => 'required',
            'legal_person' => 'required',
            'store_address' => 'required',
            'registered_capital' => 'required',
            'date_of_establishment' => 'required',
            'emergency_contact' => 'required',
            'emergency_contact_phone' => 'required',
            'business_license_no' => 'required',
            'business_license' => 'required',
            'general_taxpayer_certificate' => 'required',
            'class_id' => 'required',
            'community_id' => 'required'
        ], [
            'store_name.required' => '请填写企业名称',
            'legal_person.required' => '请填写法人',
            'store_address.required' => '请填写企业地址',
            'registered_capital.required' => '请填写注册资本',
            'date_of_establishment.required' => '请填写成立日期',
            'emergency_contact.required' => '请填写联系人',
            'emergency_contact_phone.required' => '请填写联系人电话',
            'business_license_no.required' => '请填写营业执照号',
            'business_license.required' => '请上传营业执照图片',
            'general_taxpayer_certificate.required' => '请上传一般人纳税证明',
            'class_id.required' => '请选择店铺分类',
            'class_id.community_id' => '请选择小区分类'
        ]);
        if ($validator->fails()) {
            return $this->format_error(($validator->errors()->first()));
        }
        $arr = array_merge($arr, $arr1);
        $credentials = request($arr);
        $user_model = new User();
        if ($user_model->where($username, $credentials[$username])->exists()) {
            return $this->format_error(__('auth.user_exists'));
        }
        $sms_log_model = new SmsLog();


        $randNickName = $credentials[$username] . '_' . mt_rand(100, 999);
        $user_model->username = $randNickName;
        $user_model->phone = $credentials[$username];
        $user_model->nickname = $randNickName;
        $user_model->ip = request()->getClientIp();
        $user_model->inviter_id = request()->inviter_id ?? 0;
        $user_model->password = Hash::make($credentials['password']);
        $user_model->pay_password = Hash::make($credentials['password']);
        $bl = $user_model->save();
        if ($bl) {//创建店铺
            (new StoreService())->addStore($user_model->id);
        }
        if (!$token = auth($auth)->login($user_model)) {
            return $this->format_error(__('auth.error'));
        }

        if (!$userInfo = $this->getUserInfo($auth)) {
            return $this->format_error(__('auth.user_error'));
        }
        // 登录送积分
        $config_service = new ConfigService();
        $config_service->giveIntegral('login');

        $data = [
            'token' => $token,
            'user_info' => $userInfo,
        ];
        return $this->format($data, '申请成功请耐心等待审核结果');
    }

    // 获取用户信息

    public function forgetPassword($username = 'username', $auth = 'user')
    {
        $credentials = request([$username, 'password', 're_password', 'code']);
        $user_model = new User();
        if (!$user_model->where($username, $credentials[$username])->exists()) {
            return $this->format_error(__('auth.user_not_exists'));
        }
        $sms_log_model = new SmsLog();
        if (empty($smsInfo = $sms_log_model->where([
            'ip' => request()->getClientIp(),
            'content' => $credentials['code'],
            'status' => 1,
            $username => $credentials[$username],
        ])->first())) {
            return $this->format_error(__('auth.sms_error'));
        }

        // 验证码失效 十分钟
        $ct = strtotime($smsInfo->created_at->format('Y-m-d H:i:s'));
        if (($ct + 600) < time()) {
            return $this->format_error(__('auth.sms_invalid'));
        }

        $user_model = $user_model->where($username, $credentials[$username])->first();
        $user_model->ip = request()->getClientIp();
        $user_model->password = Hash::make($credentials['password']);
        $user_model->save();

        // $credentials2 = request([$username, 'password']);
        if (!$token = auth($auth)->login($user_model)) {
            return $this->format_error(__('auth.error'));
        }

        if (!$userInfo = $this->getUserInfo($auth)) {
            return $this->format_error(__('auth.user_error'));
        }

        $data = [
            'token' => $token,
            'user_info' => $userInfo,
        ];

        return $this->format($data);
    }

    // 检测用户是否登陆

    public function checkLogin($auth = 'user', $seller = false)
    {

        // 查看是否携带token
        if (!auth($auth)->parser()->setRequest(request())->hasToken()) {
            return $this->format_error(__('auth.no_token'));
        }

        try {
            $id = auth($auth)->payload()->get('sub');
            if (!auth($auth)->byId($id)) { // 判断是否失效
                return $this->format_error(__('auth.no_token'));
            }
        } catch (\Exception $e) {
            return $this->format_error(__('auth.error_token'));
        }

        if ($seller) {
            $stores_model = new Store();
            $store_info = $stores_model->select('id', 'store_name', 'store_logo')->where('user_id', auth($auth)->id())->first();
            if (!$store_info) {
                return $this->format_error(__('auth.error_token'));
            }
            return $this->format($store_info);
        }

        return $this->format(new UserCheckLogin($this->getUserInfo($auth)));

    }

    /**
     * 修改用户资料 function
     *
     * @param string $auth 前端允许修改和后台允许修改
     * @return void
     * @Description
     * @author hg <www.qingwuit.com>
     */
    public function editUser($auth = 'user')
    {
        $user_service = new UserService();
        $user_info = $user_service->getUserInfo();

        $user_model = User::find($user_info['id']);

        // 昵称
        if (isset(request()->nickname)) {
            $user_model->nickname = request()->nickname;
        }
        // 头像
        if (isset(request()->avatar)) {
            $user_model->avatar = request()->avatar;
        }
        // 用户名
        if (isset(request()->username)) {
            $user_model->username = request()->username;
        }
        // 性别
        if (isset(request()->sex)) {
            $user_model->sex = abs(intval(request()->sex));
        }
        // 密码
        if (
            (isset(request()->password) && !empty(request()->password)) ||
            (isset(request()->pay_password) && !empty(request()->pay_password)) ||
            (isset(request()->phone) && !empty(request()->phone))
        ) {
            // 判断
            if ($auth == 'user') {
                if (!isset(request()->code) || empty(request()->code)) {
                    return $this->format_error(__('users.edit_code_error'));
                }

                $sms_log_model = new SmsLog();
                if (empty($smsInfo = $sms_log_model->where([
                    'ip' => request()->getClientIp(),
                    'content' => request()->code,
                    'status' => 1,
                    'phone' => $user_model->phone,
                ])->first())) {
                    return $this->format_error(__('auth.sms_error'));
                }

                // 验证码失效 十分钟
                $ct = strtotime($smsInfo->created_at->format('Y-m-d H:i:s'));
                if (($ct + 600) < time()) {
                    return $this->format_error(__('auth.sms_invalid'));
                }
            }

            if (isset(request()->password) || !empty(request()->password)) {
                $user_model->password = Hash::make(request()->password);
            }
            if (isset(request()->pay_password) || !empty(request()->pay_password)) {
                if (strlen(request()->pay_password) != 6) {
                    return $this->format_error(__('users.pay_password_len'));
                }
                $user_model->pay_password = md5($user_model->id . request()->pay_password);
            }
            if (isset(request()->phone) || !empty(request()->phone)) {
                $sms_service = new SmsService();
                $phone_check = $sms_service->check_phone(request()->phone);
                if (!$phone_check) {
                    return $this->format_error(__('sms.phone_error'));
                }
                $user_model->phone = md5($user_model->id . request()->phone);
            }

        }
        $user_model->save();
        return $this->format([]);
    }

    /**
     * Notes: 通过openid检查用户是否存在
     * User: lstink
     * Date: 2021/3/1
     * Time: 5:57 下午
     * @param $openid 'openid'
     */
    public function checkUserIsExistsByOpenid($session_info)
    {
        $user = User::where('openid', $session_info['openid'])->first();
        if ($user) {
            //存在则更新unionid
            $user->unionid = $session_info['unionid'];
            $user->save();
        }
        return $user;
    }

    /**
     * Notes: 微信认证
     * User: lstink
     * Date: 2021/3/2
     * Time: 1:57 下午
     * @param $openid
     * @return array
     */
    public function wechatAuth($user_model)
    {
        if ($user_model['status'] == 0) {
            return $this->format_error(__('auth.no_examine'));
        }
        //更新登录信息
        $user_model->login_time = now();
        $user_model->last_login_time = $user_model['login_time'];
        $user_model->ip = request()->getClientIp();
        //更新物业id
        $user_model->property_id = $user_model['estate']['property_id'];
        $user_model->save();
        if (!$token = auth('user')->login($user_model)) {
            // 认证失败，不存在该用户
            return $this->format_error(__('auth.error'));
        }
        $user_model->phone_str = substr_replace($user_model->phone,'****',3,4);
        $data = [
            'token' => $token,
            'userInfo' => $user_model
        ];
        $room_info = (new HouseService())->getRoomInfoByUserId($user_model['id']);
        if ($room_info['status'] === true) {
            $data['userInfo']['community'] = $room_info['data']['community'];
            $data['userInfo']['roomInfo'] = $room_info['data']['roomInfo'];
        }
        return $this->format($data);
    }

    public function registerMini()
    {
        $user_model = new User();
        $auth = 'user';
        $openId = request()->open_id;

        try {
            DB::beginTransaction();
            //判断验证码是否过期
            $created_at = DB::table('sms_logs')->where(['phone' => request()->phone, 'name' => 'register', 'content' => request()->sms_code])
                ->orderBy('created_at', 'desc')
                ->value('created_at');

            if (!$created_at) {
                return $this->format_error(__('请输入正确的验证码'));
            } else {
                $ct = strtotime($created_at);
                if (($ct + 300) < time()) {
                    return $this->format_error(__('sms.code_error'));
                }
            }

            //判断账户是否重复
            $exit = $user_model->where('phone', request()->phone)->first();
            if (!empty($exit)) {
                return $this->format_error(__('auth.user_exists'));
            }
            /*if (request()->password != request()->confirm_pass) {
                return $this->format_error(__('auth.passwords_differ'));
            }*/
            // 判断是否授权过
            $userInfo = $user_model->where('openid', $openId)->first();
            // 不存在则开始创建
            if (!$userInfo) {
                $user_model->openid = $openId;
                $user_model->username = request()->username;
                $user_model->ip = request()->getClientIp();
                $user_model->phone = request()->phone;
                //$user_model->password = Hash::make(request()->password);
                $user_model->community_id = request()->community_id;
                $user_model->room_id = request()->room_id;
                $user_model->nickname = request()->nickname;
                $user_model->sex = request()->sex;
                $user_model->avatar = request()->avatar;
                //根据小区id查询物业id
                $user_model->property_id = Community::getPropertId(request()->community_id);
                $user_model->province_id = request()->province_id;
                $user_model->city_id = request()->city_id;
                $user_model->area_id = request()->area_id;
                $user_model->address = request()->address;
                $user_model->unionid = request()->unionid;
                $user_model->save();
                $user_id = $user_model->id;
            } else {
                $user_id = $userInfo->id;
            }
            $user_info = User::where('id', $user_id)->first();


            $user_model->ip = request()->getClientIp();
            $user_model->save();

            if (!$token = auth($auth)->login($user_info)) {
                return $this->format_error(__('auth.error'));
            }

            if (!$userInfo = $this->getUserInfo($auth)) {
                return $this->format_error(__('auth.user_error'));
            }

            //获取用户数据
            $newInfo = $user_model->find($user_id);
            $newInfo->phone_str = substr_replace($newInfo->phone,'****',3,4);
            $arr = (new HouseService())->getRoomInfoByUserId($user_id);
            $newInfo->community = '暂无信息';
            $newInfo->roomInfo = '暂无信息';
            if ($arr['status']) {
                $newInfo->community = $arr['data']['community'];
                $newInfo->roomInfo = $arr['data']['roomInfo'];
            }

            $data = [
                'token' => $token,
                'userInfo' => $newInfo,
            ];

            // 提交事务
            DB::commit();
            return $this->format($data);
        } catch (\Exception $e) {
            return $this->format_error($e->getMessage());
        }
    }


    /**
     * 2021/3/15--22:42
     * @param $type 1= 加 2=减
     * @param $integral 积分数量
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:setIntegral
     * @effect:积分设置
     */
    public function setIntegral($type = 1, $integral, $user_id)
    {
        $model = new User();
        $user_info = $model->where('id', $user_id)->first();
        if ($type == 1) {
            $user_info->integral = $user_info->integral += $integral;
        } else if ($type == 2) {
            $user_info->integral = $user_info->integral -= $integral;
        }
        $user_info->save();
    }

    /**
     * 2021/3/16--14:14
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getUserInfoFiled
     * @effect:获取用户某一字段的值
     */
    public function getUserInfoFiled($filed, $id)
    {
        $model = new User();
        $user_info = $model->where('id', $id)->first()->toArray();
        return $user_info[$filed];
    }


    /**
     * 2021/3/17--11:33
     * @param string $auth
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:editPhone
     * @effect:修改手机号
     */
    public function editPhone()
    {
        $user_service = new UserService();
        $user_info = $user_service->getUserInfo();

        $user_model = User::find($user_info['id']);
        //判断账户是否重复
        $exit = $user_model->where('phone', request()->phone)->first();
        if (!empty($exit)) {
            return $this->format_error(__('auth.user_exists'));
        }
        if (isset(request()->phone) || !empty(request()->phone)) {
            $sms_service = new SmsService();
            $phone_check = $sms_service->check_phone(request()->phone);
            if (!$phone_check) {
                return $this->format_error(__('sms.phone_error'));
            }
            //判断验证码是否过期
            $created_at = DB::table('sms_logs')->where(['phone' => request()->phone, 'name' => 'changePhone', 'content' => request()->sms_code])
                ->orderBy('created_at', 'desc')
                ->value('created_at');

            if (!$created_at) {
                return $this->format_error(__('请输入正确的验证码'));
            } else {
                $ct = strtotime($created_at);
                if (($ct + 300) < time()) {
                    return $this->format_error(__('sms.code_error'));
                }
            }
            $user_model->phone = request()->phone;
        }
        $user_model->save();
        return $this->format([]);
    }

}
